﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Linq;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using FlyHorse.LIMS.WinApp.LanguageResource;
using FlyHorse.LIMS.Model;
using DevExpress.XtraCharts;
using FlyHorse.LIMS.WinApp.Utils;

namespace FlyHorse.LIMS.WinApp.DataAnalyzeFroms.CurveForms
{
    public partial class CurveForm : DevExpress.XtraEditors.XtraForm
    {
        BLL.ToolBll toolBll = new BLL.ToolBll();
        OJCB4Entities db = new OJCB4Entities();
        public CurveForm()
        {
            InitializeComponent();
        }

        private void CurveForm_Load(object sender, EventArgs e)
        {
            //绑定报告类型
            repositoryItemLookUpEdit_reportType.DataSource = toolBll.GetReportTyepList();
            //绑定样品名称
            repositoryItemSearchLookUpEdit_goods.DataSource = toolBll.GetAllGoodList();
            repositoryItemLookUpEdit_TestItem.DataSource = toolBll.GetAllTestItemList();
            repositoryItemLookUpEdit_customer.DataSource = toolBll.GetCustomerList();
            repositoryItemLookUpEdit_samplingPlace.DataSource = toolBll.GetSamplingPlaceList();
            repositoryItemLookUpEdit_placeMix.DataSource = toolBll.GetMixSamplingPlaceList();
        }

        private void barButtonItem_search_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (this.barEditItem_reportType.EditValue == null)
            {
                XtraMessageBox.Show(ResourceOverall.InputNull);
                return;
            }
            if (this.barEditItem_goods.EditValue == null)
            {
                XtraMessageBox.Show(ResourceOverall.InputNull);
                return;
            }
            if (this.barEditItem_TestItem.EditValue == null)
            {
                XtraMessageBox.Show(ResourceOverall.InputNull);
                return;
            }

            object value = barEditItem_reportType.EditValue;


            if (value != null)
            {

                string type = value.ToString();
                if (type == "1")  //原材料检验报告
                {
                    LoadRawReport();
                }
                else if (type == "2")   //过程检验报告
                {
                    LoadSemiReport();
                }
                else if (type == "3")  //出厂检验报告
                {
                    LoadProductReport();
                }
                else if (type == "4")  //成品报告
                {
                    LoadMixReport();
                }
            }

        }

        private void barEditItem_reportType_EditValueChanged(object sender, EventArgs e)
        {
            object value = barEditItem_reportType.EditValue;
            if (value != null)
            {
                string type = value.ToString();
                if (type == "1")
                {
                    barEditItem_place.Enabled = false;
                    barEditItem_MixPlace.Enabled = false;
                    barEditItem_Customer.Enabled = false;
                }
                else if (type == "2")
                {
                    barEditItem_place.Enabled = true;
                    barEditItem_MixPlace.Enabled = false;
                    barEditItem_Customer.Enabled = false;
                }
                else if (type == "3")
                {
                    barEditItem_place.Enabled = false;
                    barEditItem_MixPlace.Enabled = false;
                    barEditItem_Customer.Enabled = true;
                }
                else if (type == "4")
                {
                    barEditItem_place.Enabled = false;
                    barEditItem_MixPlace.Enabled = true;
                    barEditItem_Customer.Enabled = false;
                }

            }
            else
            {
                barEditItem_place.Enabled = false;
                barEditItem_MixPlace.Enabled = false;
                barEditItem_Customer.Enabled = false;
            }
        }

        private void LoadRawReport()
        {
            string goodsID = this.barEditItem_goods.EditValue.ToString();
            string testItemID = this.barEditItem_TestItem.EditValue.ToString();
            Good goods = db.Goods.Find(goodsID);
            TestItem testItem = db.TestItems.Find(testItemID);
            var models = db.ReportRawResults.Where(m => m.ReportRaw.GoodsID == goodsID && m.TestItemID == testItemID);
            if (this.barEditItem_dateStart.EditValue != null)
            {
                DateTime dateStart = Convert.ToDateTime(this.barEditItem_dateStart.EditValue);
                models = models.Where(m => m.ReportRaw.SendDate >= dateStart);
            }
            if (this.barEditItem_deteEnd.EditValue != null)
            {
                DateTime dateEnd = Convert.ToDateTime(this.barEditItem_deteEnd.EditValue);
                models = models.Where(m => m.ReportRaw.SendDate <= dateEnd);
            }
            models = models.OrderBy(m => m.ReportRaw.SendDate);
            if (models.Count() == 0)
            {
                XtraMessageBox.Show("没有查询出数据！");
                return;
            }

            splashScreenManager1.ShowWaitForm();

            DataTable table = new DataTable("Table1");
            // Add two columns to the table.
            table.Columns.Add("Argument", typeof(string));
            table.Columns.Add("Value", typeof(decimal));
            DataRow row = null;
            List<double> dataList = new List<double>();
            foreach (var model in models)
            {
                if (!String.IsNullOrEmpty(model.TestValue))
                {
                    row = table.NewRow();
                    row["Argument"] = model.ReportRaw.SendDate;
                    row["Value"] = model.TestValue;
                    table.Rows.Add(row);
                    dataList.Add(Convert.ToDouble(model.TestValue));
                }
            }

            Series seriesMain = new Series(goods.GoodsName + testItem.EnglishName, ViewType.Line);
            this.chartControl1.Series.Add(seriesMain);
            // Generate a data table and bind the series to it.
            seriesMain.DataSource = table;
            // Specify data members to bind the series.
            seriesMain.ArgumentScaleType = ScaleType.Auto;
            seriesMain.ArgumentDataMember = "Argument";
            seriesMain.ValueScaleType = ScaleType.Numerical;
            seriesMain.ValueDataMembers.AddRange(new string[] { "Value" });

            XYDiagram diagram = chartControl1.Diagram as XYDiagram;
            if (diagram != null)
            {
                diagram.EnableAxisXScrolling = true;
                diagram.EnableAxisXZooming = true;
                diagram.EnableAxisYScrolling = true;
                diagram.EnableAxisYZooming = true;
            }

            StandardRaw standard = db.StandardRaws.Where(m => m.GoodsID == goodsID && m.TestItemID == testItemID).FirstOrDefault();
            if (standard != null)
            {
                Calculate(dataList, standard.MinValue, standard.MaxValue);
            }
            splashScreenManager1.CloseWaitForm();
        }

        private void LoadSemiReport()
        {
            string goodsID = this.barEditItem_goods.EditValue.ToString();
            string testItemID = this.barEditItem_TestItem.EditValue.ToString();
            Good goods = db.Goods.Find(goodsID);
            TestItem testItem = db.TestItems.Find(testItemID);
            var models = db.ReportSemiResults.Where(m => m.ReportSemi.GoodsID == goodsID && m.TestItemID == testItemID);
            if (this.barEditItem_dateStart.EditValue != null)
            {
                DateTime dateStart = Convert.ToDateTime(this.barEditItem_dateStart.EditValue);
                models = models.Where(m => m.ReportSemi.SendDate >= dateStart);
            }
            if (this.barEditItem_deteEnd.EditValue != null)
            {
                DateTime dateEnd = Convert.ToDateTime(this.barEditItem_deteEnd.EditValue);
                models = models.Where(m => m.ReportSemi.SendDate <= dateEnd);
            }

            if (barEditItem_place.EditValue != null)
            {
                string placeID = barEditItem_place.EditValue.ToString();
                models = models.Where(m => m.ReportSemi.SamplingPlaceID == placeID);
            }
            models = models.OrderBy(m => m.ReportSemi.SendDate);
            barEditItem_count.EditValue = models.Count();
            if (models.Count() == 0)
            {
                XtraMessageBox.Show("没有查询出数据！");
                return;
            }

            splashScreenManager1.ShowWaitForm();
            DataTable table = new DataTable("Table1");
            // Add two columns to the table.
            table.Columns.Add("Argument", typeof(string));
            table.Columns.Add("Value", typeof(decimal));
            DataRow row = null;
            List<double> dataList = new List<double>();
            foreach (var model in models)
            {
                if (!String.IsNullOrEmpty(model.TestValue))
                {
                    row = table.NewRow();
                    row["Argument"] = model.ReportSemi.SendDate;
                    row["Value"] = model.TestValue;
                    table.Rows.Add(row);
                    dataList.Add(Convert.ToDouble(model.TestValue));
                }
            }

            Series seriesMain = new Series(goods.GoodsName +"-"+ testItem.EnglishName, ViewType.Line);
            this.chartControl1.Series.Add(seriesMain);
            // Generate a data table and bind the series to it.
            seriesMain.DataSource = table;
            // Specify data members to bind the series.
            seriesMain.ArgumentScaleType = ScaleType.Auto;
            seriesMain.ArgumentDataMember = "Argument";
            seriesMain.ValueScaleType = ScaleType.Numerical;
            seriesMain.ValueDataMembers.AddRange(new string[] { "Value" });

            XYDiagram diagram = chartControl1.Diagram as XYDiagram;
            if (diagram != null)
            {
                diagram.EnableAxisXScrolling = true;
                diagram.EnableAxisXZooming = true;
                diagram.EnableAxisYScrolling = true;
                diagram.EnableAxisYZooming = true;
            }

            if (barEditItem_place.EditValue != null)
            {
                string placeID = barEditItem_place.EditValue.ToString();
                StandardSemi standard = db.StandardSemis.Where(m => m.GoodsID == goodsID && m.TestItemID == testItemID && m.SamplingPlaceID == placeID).FirstOrDefault();
                if (standard != null)
                {
                    Calculate(dataList, standard.MinValue, standard.MaxValue);
                }
            }
            splashScreenManager1.CloseWaitForm();
        }

        private void LoadMixReport()
        {
            string goodsID = this.barEditItem_goods.EditValue.ToString();
            string testItemID = this.barEditItem_TestItem.EditValue.ToString();
            Good goods = db.Goods.Find(goodsID);
            TestItem testItem = db.TestItems.Find(testItemID);
            var models = db.ReportMixResults.Where(m => m.ReportMix.GoodsID == goodsID && m.TestItemID == testItemID);
            if (this.barEditItem_dateStart.EditValue != null)
            {
                DateTime dateStart = Convert.ToDateTime(this.barEditItem_dateStart.EditValue);
                models = models.Where(m => m.ReportMix.SendDate >= dateStart);
            }
            if (this.barEditItem_deteEnd.EditValue != null)
            {
                DateTime dateEnd = Convert.ToDateTime(this.barEditItem_deteEnd.EditValue);
                models = models.Where(m => m.ReportMix.SendDate <= dateEnd);
            }
            if (this.barEditItem_MixPlace.EditValue != null)
            {
                string placeID = Convert.ToString(barEditItem_MixPlace.EditValue);
                models = models.Where(m => m.ReportMix.SamplingPlaceMixID == placeID);
            }
            models = models.OrderBy(m => m.ReportMix.SendDate);
            if (models.Count() == 0)
            {
                XtraMessageBox.Show("没有查询出数据！");
                return;
            }
            splashScreenManager1.ShowWaitForm();
            DataTable table = new DataTable("Table1");
            // Add two columns to the table.
            table.Columns.Add("Argument", typeof(string));
            table.Columns.Add("Value", typeof(decimal));
            DataRow row = null;
            List<double> dataList = new List<double>();
            foreach (var model in models)
            {
                if (!String.IsNullOrEmpty(model.TestValue))
                {
                    row = table.NewRow();
                    row["Argument"] = model.ReportMix.SendDate;
                    row["Value"] = model.TestValue;
                    table.Rows.Add(row);
                    dataList.Add(Convert.ToDouble(model.TestValue));
                }
            }

            Series seriesMain = new Series(goods.GoodsName + testItem.EnglishName, ViewType.Line);
            this.chartControl1.Series.Add(seriesMain);
            // Generate a data table and bind the series to it.
            seriesMain.DataSource = table;
            // Specify data members to bind the series.
            seriesMain.ArgumentScaleType = ScaleType.Auto;
            seriesMain.ArgumentDataMember = "Argument";
            seriesMain.ValueScaleType = ScaleType.Numerical;
            seriesMain.ValueDataMembers.AddRange(new string[] { "Value" });

            XYDiagram diagram = chartControl1.Diagram as XYDiagram;
            if (diagram != null)
            {
                diagram.EnableAxisXScrolling = true;
                diagram.EnableAxisXZooming = true;
                diagram.EnableAxisYScrolling = true;
                diagram.EnableAxisYZooming = true;
            }

            StandardSemi standard = db.StandardSemis.Where(m => m.GoodsID == goodsID && m.TestItemID == testItemID && m.SamplingPlaceID == "2").FirstOrDefault();
            if (standard != null)
            {
                Calculate(dataList, standard.MinValue, standard.MaxValue);
            }
            splashScreenManager1.CloseWaitForm();
        }


        private void LoadProductReport()
        {
            string goodsID = this.barEditItem_goods.EditValue.ToString();
            string testItemID = this.barEditItem_TestItem.EditValue.ToString();
            Good goods = db.Goods.Find(goodsID);
            TestItem testItem = db.TestItems.Find(testItemID);
            var models = db.ReportProductResults.Where(m => m.ReportProduct.GoodsID == goodsID && m.TestItemID == testItemID);
            if (this.barEditItem_dateStart.EditValue != null)
            {
                DateTime dateStart = Convert.ToDateTime(this.barEditItem_dateStart.EditValue);
                models = models.Where(m => m.ReportProduct.DateProduced >= dateStart);
            }
            if (this.barEditItem_deteEnd.EditValue != null)
            {
                DateTime dateEnd = Convert.ToDateTime(this.barEditItem_deteEnd.EditValue);
                models = models.Where(m => m.ReportProduct.DateProduced <= dateEnd);
            }
            if (this.barEditItem_Customer.EditValue != null)
            {
                string custID = Convert.ToString(barEditItem_Customer.EditValue);
                models = models.Where(m => m.ReportProduct.CustomerID == custID);
            }
            models = models.OrderBy(m => m.ReportProduct.DateProduced);
            if (models.Count() == 0)
            {
                XtraMessageBox.Show("没有查询出数据！");
                return;
            }
            splashScreenManager1.ShowWaitForm();
            DataTable table = new DataTable("Table1");
            // Add two columns to the table.
            table.Columns.Add("Argument", typeof(string));
            table.Columns.Add("Value", typeof(decimal));
            DataRow row = null;
            List<double> dataList = new List<double>();
            foreach (var model in models)
            {
                if (!String.IsNullOrEmpty(model.TestValue))
                {
                    row = table.NewRow();
                    row["Argument"] = model.ReportProduct.DateProduced;
                    row["Value"] = model.TestValue;
                    table.Rows.Add(row);
                    dataList.Add(Convert.ToDouble(model.TestValue));
                }
            }

            Series seriesMain = new Series(goods.GoodsName + testItem.EnglishName, ViewType.Line);
            this.chartControl1.Series.Add(seriesMain);
            // Generate a data table and bind the series to it.
            seriesMain.DataSource = table;
            // Specify data members to bind the series.
            seriesMain.ArgumentScaleType = ScaleType.Auto;
            seriesMain.ArgumentDataMember = "Argument";
            seriesMain.ValueScaleType = ScaleType.Numerical;
            seriesMain.ValueDataMembers.AddRange(new string[] { "Value" });

            XYDiagram diagram = chartControl1.Diagram as XYDiagram;
            if (diagram != null)
            {
                diagram.EnableAxisXScrolling = true;
                diagram.EnableAxisXZooming = true;
                diagram.EnableAxisYScrolling = true;
                diagram.EnableAxisYZooming = true;
            }

            if (this.barEditItem_Customer.EditValue != null)
            {
                string custID = Convert.ToString(barEditItem_Customer.EditValue);
                StandardCustomer standard = db.StandardCustomers.Where(m => m.GoodsID == goodsID && m.TestItemID == testItemID && m.CustomerID == custID).FirstOrDefault();
                if (standard != null)
                {
                    Calculate(dataList, standard.MinValue, standard.MaxValue);
                }
            }
            splashScreenManager1.CloseWaitForm();
        }

        public void Calculate(List<double> dataList, string lsl, string usl)
        {
            int count = dataList.Count();
            double? minValue = SummaryCalculate.GetMinValue(dataList);
            double? maxValue = SummaryCalculate.GetMaxValue(dataList);
            double? avgValue = SummaryCalculate.GetAvgValue(dataList);
            double? midValue = SummaryCalculate.GetMidValue(dataList);
            double? rangeValue = SummaryCalculate.GetRangeValue(dataList);
            double? sigma = SummaryCalculate.GetSigmaValue(dataList);
            double? sValue = SummaryCalculate.GetSValue(dataList);
            double? caValue = null;
            double? cpValue = null;
            double? cpkValue = null;
            if (!String.IsNullOrEmpty(lsl) && !String.IsNullOrEmpty(usl))
            {
                double low = Convert.ToDouble(lsl);
                double up = Convert.ToDouble(usl);
                caValue = SummaryCalculate.GetCAValue(dataList, low, up);
                cpValue = SummaryCalculate.GetCPValue(dataList, low, up);
                cpkValue = SummaryCalculate.GetCPKValue(dataList, low, up);
            }
            else if (String.IsNullOrEmpty(lsl) && !String.IsNullOrEmpty(usl))  //只有上限
            {
                double up = Convert.ToDouble(usl);
                cpValue = SummaryCalculate.GetCPValue(dataList, up, true);
            }
            else if (!String.IsNullOrEmpty(lsl) && String.IsNullOrEmpty(usl))  //只有下限
            {
                double low = Convert.ToDouble(lsl);
                cpValue = SummaryCalculate.GetCPValue(dataList, low, false);
            }
            this.barEditItem_count.EditValue = count;
            this.barEditItem_minValue.EditValue = minValue;
            this.barEditItem_avgValue.EditValue = avgValue;
            this.barEditItem_maxValue.EditValue = maxValue;
            this.barEditItem_midValue.EditValue = midValue;
            this.barEditItem_rangeValue.EditValue = rangeValue;
            this.barEditItem_sigma.EditValue = sigma;
            this.barEditItem_sValue.EditValue = sValue;
            this.barEditItem_caValue.EditValue = caValue;
            this.barEditItem_cpValue.EditValue = cpValue;
            this.barEditItem_cpkValue.EditValue = cpkValue;

        }



        private void barButtonItem_clear_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            barEditItem_reportType.EditValue = null;
            barEditItem_goods.EditValue = null;
            barEditItem_TestItem.EditValue = null;
            barEditItem_dateStart.EditValue = null;
            barEditItem_deteEnd.EditValue = null;
            barEditItem_place.EditValue = null;
            barEditItem_MixPlace.EditValue = null;
            barEditItem_Customer.EditValue = null;

            barEditItem_count.EditValue = "";
            barEditItem_minValue.EditValue = null;
            barEditItem_maxValue.EditValue = null;
            barEditItem_avgValue.EditValue = null;
            barEditItem_midValue.EditValue = null;
            barEditItem_rangeValue.EditValue = null;
            barEditItem_sigma.EditValue = null;
            barEditItem_sValue.EditValue = null;
            barEditItem_caValue.EditValue = null;
            barEditItem_cpValue.EditValue = null;
            barEditItem_cpkValue.EditValue = null;

            for (int i = 0; i < this.chartControl1.Series.Count; )
            {
                this.chartControl1.Series.RemoveAt(i);
            }
        }

        private void barButtonItem_ExportExcel_ItemClick_1(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            splashScreenManager1.ShowWaitForm();
            DataSet set = new DataSet();
            foreach (Series Serie in chartControl1.Series)
            {

                DataTable dataTable =(DataTable) Serie.DataSource;
                DataTable tableTemp = dataTable.Copy();
                tableTemp.Namespace = Serie.Name;
                //tableTemp.TableName = Serie.Name;
                try
                {
                    set.Tables.Add(tableTemp);
                }
                catch (Exception ex)
                {
                    if (ex.Message.Contains("DataSet"))
                    {
                        splashScreenManager1.CloseWaitForm();
                        string msg = String.Format(ResourceOverall.CurveNameExists, Serie.Name);
                        XtraMessageBox.Show(msg);
                        return;
                    }
                    else
                    {
                        splashScreenManager1.CloseWaitForm();
                        XtraMessageBox.Show(ex.Message);
                        return;
                    }
                    
                }
                
            }
            splashScreenManager1.CloseWaitForm();
            ExportExcelForm form = new ExportExcelForm(set);
            form.Show();
        }

    }
}